<?php
/**
 * Skyline :: Patterns & component framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Skyline\Comparator;

use InvalidArgumentException;
use Skyline\Structure\Sequence\ListInterface;

/**
 * Comparator that uses an ordered list of values
 * 
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class FixedOrderComparator implements ComparatorInterface
{
	/**
	 * @var FixedOrderComparatorBehavior
	 */
	protected $behavior;
	
	/**
	 * @var ListInterface<mixed>
	 */
	protected $orderList;
	
	/**
	 * Class constructor
	 * 
	 * @param ListInterface<mixed> $orderList
	 * @param FixedOrderComparatorBehavior $behavior [optional] Default is UNKNOWN_THROW_EXCEPTION
	 * @return void
	 */
	public function __construct(ListInterface $orderList, FixedOrderComparatorBehavior $behavior = null)
	{
		$this->behavior = ($behavior ?: new FixedOrderComparatorBehavior(FixedOrderComparatorBehavior::UNKNOWN_THROW_EXCEPTION));
		$this->orderList = $orderList;
	}
	
	/**
	 * Compares a left value to a right value and returns an integer comparison
	 * 
	 * @param mixed $left
	 * @param mixed $right
	 * @return int (-1 = less than, 0 = equal, 1 = greater than)
	 */
	public function compare($left, $right)
	{
		$leftOrder = $this->getOrder($left);
		$rightOrder = $this->getOrder($right);
		
		if(is_null($leftOrder) || is_null($rightOrder)) {
			switch($this->behavior) {
				case FixedOrderComparatorBehavior::UNKNOWN_THROW_EXCEPTION:
					throw new InvalidArgumentException('Value does not exist in order list');
				case FixedOrderComparatorBehavior::UNKNOWN_BEFORE:
					return (is_null($leftOrder) ? (is_null($rightOrder) ? 0 : -1) : 1);
				case FixedOrderComparatorBehavior::UNKNOWN_AFTER:
					return (is_null($leftOrder) ? (is_null($rightOrder) ? 0 : 1) : -1);
			}
		}
		return ($leftOrder > $rightOrder ? 1 : ($leftOrder < $rightOrder ? -1 : 0));
	}
	
	/**
	 * Returns the list of values and the order they should be sorted in
	 * @return ListInterface
	 */
	public function getOrderList()
	{
		return $this->orderList;
	}
	
	/**
	 * Returns the order that an input value should be sorted to
	 * 
	 * @param mixed $input
	 * @return int|null Returns null if input value not in order list
	 */
	protected function getOrder($input)
	{
		return $this->orderList->indexOf($input);
	}
}